package org.gpf;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDOM_Test {

	public static void main(String[] args) throws Exception {
		parseXML("res/books.xml");
		newXML("res/books_jdom_out.xml");
	}

	public static void parseXML(String url) throws Exception{
		
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new File(url));
		
		Element rootElement = document.getRootElement();
		List<Element>bookList = rootElement.getChildren();
		for (Element book : bookList) {
			System.out.println("书：id = " + book.getAttributeValue("id")+",isbn:" + book.getAttributeValue("isbn"));
			System.out.println("书名：" + book.getChildText("name"));
			System.out.println("作者：" + book.getChildText("author"));
			System.out.println("价格：" + book.getChildText("price"));
			System.out.println("年份：" + book.getChildText("year"));
			System.out.println("===========================");
		}
	}
	
	public static void newXML(String url) throws Exception{
		
		Element books = new Element("books");		// 创建元素节点
		Element book = new Element("book");
		Element name = new Element("name");
		Element author = new Element("author");
		Element price = new Element("price");
		Element year = new Element("year");
		Document document = new Document(books); 	// 根据根节点创建文档对象
		
		/* 设置属性和节点的内容 */
		book.setAttribute("id", "001");
		Attribute attribute = new Attribute("isbn", "1");
		book.setAttribute(attribute);
		name.setText("面向对象程序设计");
		author.setText("杰克·凯文");
		price.setText("56.3");
		year.setText("2012");
		
		/* 设置节点间的关系 */
		book.addContent(name);
		book.addContent(author);
		book.addContent(price);
		book.addContent(year);
		books.addContent(book);
		
		/* 创建Format对象，主要是让xml有一个更好的格式，并不是必须的 */
		Format format = Format.getPrettyFormat();
		format.setEncoding("utf-8");
		format.setIndent("    ");
		
		/* 将文档写入到输出流 */
		XMLOutputter outputter = new XMLOutputter(format);
		outputter.output(document, new FileOutputStream(url));
	}
}
